//
//  XYUserAccount.swift
//  01-新浪微博
//
//  Created by 陈许亚 on 16/3/9.
//  Copyright © 2016年 cxy. All rights reserved.
//
/*1.字典转模型
   2.保存数据
    3.对外提供获取数据的方式
*/
import UIKit
import AFNetworking
import SVProgressHUD
class XYUserAccount: NSObject {
    
    //定义单例对象
    static let sharedAccount = XYUserAccount()
    
    //用于调用access_token，接口获取授权后的access token。
    var access_token: String?
    
    //用于调用access_token，接口获取授权后的access token。当前token过多少秒后过期
    var expires_in: NSTimeInterval = 0 {
        didSet{
            expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    //普通账户的过期日期是3天，开发者账户的过去日期是5年
    var expires_date: NSDate?
    
    //access_token的生命周期（该参数即将废弃，开发者请使用expires_in）废弃的参数，在接口返回的数据中不能删除，接口返回的数据的字段只能增加，不能减少
    //var remind_in: String?
    
    //当前授权用户的UID
    var uid:String?
    
    //用户名
    var name:String?
    
    //当前用户头像
    var avatar_large:String? {
        didSet{
            
            headImage = NSURL(string: avatar_large ?? "")
        }
    }
    
    
    var headImage: NSURL?
    
    //计算型属性
    var userLogin: Bool {
        //，如果token不为nil，说明已经登录
        
        return access_token != nil
    }
    
    override private init() {
        super.init()
        //加载用户数据
        self.loadUserInfo()
    }
    //未定义的key
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
        //只读属性
        let keys = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        return accountDict.description
    }

}

extension XYUserAccount {
    //保存用户数据
    func saveUserInfo(dict: [String : AnyObject]){
        
        //用kvc给属性赋值
        self.setValuesForKeysWithDictionary(dict)
        //以字典的形式保存当前属性
        let userDefault = NSUserDefaults.standardUserDefaults()
        //获取当前对象字典的信息
        let keys = ["access_token","expires_in","uid","name","avatar_large"]
        
        let accountDict = self.dictionaryWithValuesForKeys(keys)
        //将用户信息保存到沙盒
        userDefault.setObject(accountDict, forKey: "cn.cxy.account")
        //沙盒同步
        userDefault.synchronize()
        //打印沙盒路径
        print(NSHomeDirectory())
        
    }
    
    func loadUserInfo(){
        //从偏好设置中获取获取数据
       guard let dict = NSUserDefaults.standardUserDefaults().objectForKey("cn.cxy.account") as? [String: AnyObject] else {
            
            return
        }
        //将字典数据转模型
        self.setValuesForKeysWithDictionary(dict)
        
        //判断token是否过期，如果过期将当前用户设置为未登录
        //如果token 不为空，说明登录，如果token为nil，说明未登录
        if self.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
            //如果过期日期大于当前日期，说明没过期
            print("当前用户token没有过期")
        }else{
            print("当前用户token已经过期")
            self.access_token = nil
            
        }
        print(self)
    }
    
    
}
extension XYUserAccount {
    //获取token数据
    func loadAccessToken(code: String,finished: (isSuccessed: Bool) -> ()){
        //获取access_token的url
        let urlString = "https://api.weibo.com/oauth2/access_token"
        //需要的参数
        let parameters = ["client_id" : client_id, "client_secret": client_secret,"grant_type": "authorization_code", "code": code, "redirect_uri": redirect_uri]
        
        let AFN = AFHTTPSessionManager()
        AFN.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        AFN.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //打印result ,查看结果是什么类型
            //            print(result,result?.classForCoder)
            //将result强转为[String: AnyObject]，判断是否有值，有值的话赋值给dict
            guard var dict = result as? [String: AnyObject] else {
                
//                SVProgressHUD.showErrorWithStatus("错误")
                //失败的时候需要执行闭包
                finished(isSuccessed: false)
                return
            }
            
            
            print(dict)
            //            //标示用户访问接口的权限的时效性标识
//                        let token = dict["access_token"]
            //
//                       print(token)
            //在闭包当中要调用当前对象的方法和属性的时候要用self来调用，说明上下文语境
            self.loadUserInfo(dict, finished: finished)
            
            }) { (_, error) -> Void in
                //失败的时候需要执行闭包
                finished(isSuccessed: false)
                print(error)
        }
    }
    
    //获取用户数据
    func loadUserInfo(dict: [String: AnyObject],finished: (isSuccessed: Bool) -> ()) {
        
        let token = dict["access_token"] as! String
        let uid = dict["uid"] as! String
        let urlString = "https://api.weibo.com/2/users/show.json"
        //在AFN中发起网络访问都是用字典的形式
        //字典中不能直接添加nil,可以添加空对象，[NSNull null]
        let parameters = ["access_token": token,"uid": uid]
        
        let AFN = AFHTTPSessionManager()
        AFN.GET(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            
            print(result,result?.classForCoder)
            guard var userInfoDict = result as? [String : AnyObject] else {
                
//                SVProgressHUD.showErrorWithStatus("数据格式错误")
                //失败的时候需要执行闭包
                finished(isSuccessed: false)
                
                return
            }
            //打印用户数据
            print("userInfoDict=",userInfoDict)
            //合并字典
            for (k,v) in dict {
                userInfoDict[k] = v
            }
            print("userInfoDict=======",userInfoDict)
            
            //存储用户数据
            XYUserAccount.sharedAccount.saveUserInfo(userInfoDict)
            finished(isSuccessed: true)

            
            }) { (_, error) -> Void in
                //失败的时候需要执行闭包
                finished(isSuccessed: false)
                print(error)
        }
        
        
    }
    
    

}











